package net.csdn.business.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Auther: zhangyalei
 * @Date: 2021/5/25 18:08
 * @Description:
 */
@Slf4j
public class SurvivalClamProcessor implements Runnable{
    private static final int REDIS_EXPIRE_SUCCESS = 1;

    public SurvivalClamProcessor(RedisLockUtils redisLockUtils, String key, int lockTime) {
        this.redisLockUtils = redisLockUtils;
        this.key = "lock:"+key;
        this.lockTime = lockTime;
        this.signal = Boolean.TRUE;
    }

    private RedisLockUtils redisLockUtils;
    private String key;
    private int lockTime;

    //线程关闭的标记
    private volatile Boolean signal;

    public void stop() {
        this.signal = Boolean.FALSE;
    }

    @Override
    public void run() {
        int waitTime = lockTime * 1000 * 2 / 3;
        while (signal) {
            try {
                Thread.sleep(waitTime);
                System.out.println(Thread.currentThread().getName());

                //此处如果不适用tryLockAsync会导致锁id进行变更。导致释放锁的时候报错。其中value的值的业务线程的id
                if (redisLockUtils.setEx(key,lockTime)) {
                    log.info("expandLockTime 成功，本次等待{}ms，将重置锁超时时间重置为{}s,延期的key为{}", waitTime, lockTime,key);
                } else {
                    if (log.isInfoEnabled()) {
                        log.info("expandLockTime 失败，将导致SurvivalClamConsumer中断,key:{}", key);
                    }
                    this.stop();
                }
            } catch (InterruptedException e) {
                if (log.isInfoEnabled()) {
                    log.info("SurvivalClamProcessor 处理线程被强制中断");
                }
            } catch (Exception e) {
                log.error("SurvivalClamProcessor run error", e);
            }
        }
        log.info("SurvivalClamProcessor 处理线程已停止");
    }
}
